/* Copyright (C) 2011 clueless <clueless.mmopeon@gmail.com>
 *
 * This file is part of MMO Peon.
 *
 * MMO Peon is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * MMO Peon is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with MMO Peon.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "statemachine.h"
#include <algorithm>

#include "../log.h"

bool CompareState(BaseState *a, BaseState *b)
{
    return a->Priority() < b->Priority();
}

BaseState::BaseState(uint32_t priority)
{
    this->priority = priority;
}

BaseState::~BaseState()
{
    return;
}

uint32_t BaseState::Priority() const
{
    return priority;
}

bool BaseState::Ready()
{
    return false;
}

void BaseState::Enter()
{
    return;
}

void BaseState::Update()
{
    return;
}

void BaseState::Exit()
{
    return;
}

StateMachine::StateMachine()
{
    haveActive = false;
    isSorted = false;
    activeState = 0;
}

void StateMachine::AddState(BaseState *state)
{
    isSorted = false;
    states.push_back(state);
}

void StateMachine::SortStates()
{
    isSorted = true;
    std::sort(states.begin(), states.end(), CompareState);
}

void StateMachine::Pulse()
{
    if (!isSorted)
        SortStates();

    for (auto it = states.begin(); it != states.end(); it++)
    {
        BaseState *itState = *it;
        if (itState->Ready())
        {
            // Exit any possible already existing states
            if (haveActive && itState != activeState)
            {
                haveActive = false;
                activeState->Exit();
            }

            // Set the new active state
            if (!haveActive)
            {
                haveActive = true;
                activeState = itState;
                itState->Enter();
            }
            // Update the current state
            activeState->Update();
            break;
        }
    }
}
